import datetime
#from datetime import time
#from datetime import datetime
from datetime import timedelta
import pandas as pd
from ths.codeList import Tonghuashun
import baostock as bs
from util.GetBaostockDatByDataFrame import GetBaostockDataFrame
from util.WalkDataUtil import WalkDataUtil
from others.dfcf import dfcf
from util.GetTransactionDay import GetTransactionDay
def getDay(bs, todate):
    day = todate.strftime('%Y-%m-%d')
    rs = bs.query_all_stock(day=day)
    if rs.next() == False:
        yes_time = todate + timedelta(days=-1)
        return  getDay(bs, yes_time)
    else:

        d = getNextDay(bs, todate)

    return d,todate,rs

    #return yes_time, rs

def  getNextDay(bs,todate):
        yes_time = todate + timedelta(days=-1)
        day= yes_time.strftime('%Y-%m-%d')
        rs = bs.query_all_stock(day=day)
        if rs.next() == False:
            return getNextDay(bs, yes_time)
        else:
            return  rs,yes_time


if __name__ == "__main__":
    try:
        lg = bs.login(user_id='anonymous', password='123456')
        GetTransactionDay = GetTransactionDay()
        todate = GetTransactionDay.get_now_trade_date()
        d = getNextDay(bs,todate[0])
        rs = d[0]
        yesdate = d[1]
        i=0
        df1 = []
        df =pd.DataFrame(columns=['high', 'open', 'close', 'low','ma25','bias_24','bizhi'])
        resdata = pd.DataFrame(columns=['ind', 'time', 'code','bias_24'])
        while (rs.error_code == '0') & rs.next():
            try:
                code = rs.get_row_data()[0]
                if "sh.60" in code or "sz.00" in code:
                    print(i)
                    i = i + 1
                    data = GetBaostockDataFrame().getTimeData(bs, code, 'd', 50,todate[0], todate[1])
                    walkData = WalkDataUtil().getWalkData(data)
                    d1=  walkData.iloc[0]
                    d2 = walkData.iloc[1]
                    d3 = walkData.iloc[2]
                    t1 =d1['type']
                    t2 = d2['type']
                    ind1 = d1['ind']
                    ind2 = d2['ind']
                    data1 = data.iloc[ind1]
                    data1_1 = data.iloc[ind1+1]
                    data2 = data.iloc[ind2]
                    data2_1 = data.iloc[ind2 + 1]
                    #
                    if ind1-ind2 > 5   and    t2==2 and    t1==2  and data1_1['high'] > data1['high'] :
                        t1_str = d1['time'].strftime('%Y-%m-%d')
                        t2_str = yesdate.strftime('%Y-%m-%d')
                        if t1_str == t2_str :
                            data['bias_24'] = (data['close'] - data['close'].rolling(24, min_periods=1).mean()) / data['close'].rolling(24, min_periods=1).mean() * 100
                            data['bias_24'] = round(data['bias_24'], 2)
                            data1 = data.iloc[ind1]
                            resdata = resdata.append({'bias_24':data1['bias_24'],'code': code, 'ind':  ind1-ind2, 'time': d1['time']},ignore_index=True)
            except Exception as err:
                1+1
                print(err)


        resdata = resdata.sort_values(by='ind', ascending=False)
        resdata = resdata[0:50]

        resdata = resdata.sort_values(by='bias_24', ascending=True)
        resdata = resdata[0:20]


        name = todate[0].strftime('%Y%m%d')+'反弹'
        dfcf = dfcf()
        pid =dfcf.group_create(name)
        for ind, row in resdata.iterrows():
            code = row['code'].replace('.','')
            dfcf.add(code,pid)
        print(resdata)
        print("运行完成!")
    except Exception as err:
        print("Finished with error: ", err)